package dao

import (
	"time"
	"xin-job/admin/dao/model"

	"gorm.io/gorm"
)

func RegistryUpdate(registryGroup, registryKey, registryValue string) int64 {
	var rowsAffected int64
	db.Transaction(func(tx *gorm.DB) error {
		result := tx.Model(&model.XxlJobRegistry{}).Where("registry_group = ?", registryGroup).Where("registry_key = ?", registryKey).Where("registry_value = ?", registryValue).Update("update_time", time.Now())
		if result.Error != nil {
			return result.Error
		}

		rowsAffected = result.RowsAffected
		return nil
	})
	return rowsAffected
}

func RegistrySave(registryGroup, registryKey, registryValue string) int64 {
	var rowsAffected int64

	db.Transaction(func(tx *gorm.DB) error {
		result := tx.Create(&model.XxlJobRegistry{
			RegistryGroup: registryGroup,
			RegistryKey:   registryKey,
			RegistryValue: registryValue,
			UpdateTime:    time.Now(),
		})

		if result.Error != nil {
			return result.Error
		}

		rowsAffected = result.RowsAffected
		return nil
	})
	return rowsAffected
}

func RegistryDel(registryGroup, registryKey, registryValue string) int64 {
	var rowsAffected int64

	db.Transaction(func(tx *gorm.DB) error {
		result := tx.Where("registry_group = ?", registryGroup).Where("registry_key = ?", registryKey).Where("registry_value = ?", registryValue).Delete(&model.XxlJobRegistry{})

		if result.Error != nil {
			return result.Error
		}

		rowsAffected = result.RowsAffected
		return nil
	})
	return rowsAffected
}

func FindDead(timeout int, now time.Time) []int {
	var s []model.XxlJobRegistry
	db.Where("update_time < DATE_ADD(?,INTERVAL - ? SECOND)", now, timeout).Find(&s)
	var r []int
	if len(s) > 0 {
		for _, v := range s {
			r = append(r, v.Id)
		}
	}
	return r
}

func FindAll(timeout int, now time.Time) []model.XxlJobRegistry {
	var s []model.XxlJobRegistry
	db.Where("update_time > DATE_ADD(?,INTERVAL - ? SECOND)", now, timeout).Find(&s)
	return s
}

func RemoveDead(ids []int) {
	var s []model.XxlJobRegistry
	if len(ids) > 0 {
		for _, v := range ids {
			s = append(s, model.XxlJobRegistry{Id: v})
		}
	}
	db.Delete(&s)
}
